# backend/routers/drug.py
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List

from database import async_session
from schemas import DrugListResp, DrugDetailResp, PageMeta
from utils.response import R
import crud

async def get_db():
    async with async_session() as session:
        yield session

router = APIRouter()

@router.get("/search", summary="模糊搜索药品")
async def search_drugs(
    kw: str = Query(..., description="关键字"),
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    db: AsyncSession = Depends(get_db)
):
    offset = (page - 1) * page_size
    drugs, total = await crud.search_drugs(db, kw, offset, page_size)

    data = {
        "list": [DrugListResp.model_validate(d) for d in drugs],
        "meta": PageMeta(page=page, page_size=page_size, total=total)
    }
    return R.ok(data)

@router.get("/{drug_id}", summary="药品详情")
async def drug_detail(
    drug_id: int,
    db: AsyncSession = Depends(get_db)
):
    drug = await crud.get_drug_by_id(db, drug_id)
    if not drug:
        raise HTTPException(status_code=404, detail="药品不存在")

    pics = drug.pic.split(",") if drug.pic else []
    detail = DrugDetailResp.model_validate(drug)
    detail.pics = pics
    return R.ok(detail)